import { website_list, script_execute, script_update } from '@/api/script';
import { get_global_config, update_global_config } from '@/api/global.js';
import { message } from 'ant-design-vue';

// 设置用户 token
export function set_user_token(token) {
  return localStorage.setItem('user_token', token);
}

// 获取用户 token
export function get_user_token() {
  return localStorage.getItem('user_token');
}

// 清除用户信息
export function clear_user_info() {
  localStorage.removeItem('user_token');
}

// 设置全局类目数据
export function set_global_category(data) {
  return localStorage.setItem('global_category', JSON.stringify(data));
}

// 获取全局类目数据
export async function get_global_category() {
  try {
    let local_data = localStorage.getItem('global_category');
    if (local_data) {
      return JSON.parse(local_data);
    } else {
      // return [];
      // TODO 从接口获取
      let script_id = (
        await get_global_config_by_key('GLOBAL_CATEGORY_EXTRACT')
      ).extraInfo;
      // console.log(`output->script_id`,script_id)
      let res = await script_execute(script_id, []);
      set_global_category(JSON.parse(res.data));
      return JSON.parse(res.data);
    }
  } catch (err) {
    console.error('get_global_category error', err);
    return [];
  }
}

// 获取所有站点数据
export async function get_all_site_data() {
  return debug_show(await get_global_category()).map(item => {
    return {
      site_code: item.website_code,
      site_name: item.website_name,
      site_logo_url: item.website_img_url,

      label: item.website_name, // 用于 el-select 的显示
      value: item.website_code, // 用于 el-select 的值
    };
  });
}

// 获取当前站点类目数据
export async function get_site_category_data(site_code) {
  // console.log("site_code", site_code);
  return (
    (await get_global_category())
      ?.find(item => item.website_code === site_code)
      ?.category_list?.map(item => {
        return {
          category_id: item.id,
          category_code: item.category_code,
          category_name: item.category_name,
          category_logo_url: item.category_img_url,

          label: item.nav_breadcrumb, // 用于 el-select 的显示
          value: item.category_code, // 用于 el-select 的值
        };
      }) ?? []
  );
}

// 获取站点类目详情
export async function get_site_category_detail(site_code, category_code) {
  // 先找到站点数据
  const site_data = (await get_global_category())?.find(
    item => item.website_code === site_code
  );
  if (!site_data) return null;

  // 再找到类目的数据
  const category_data = site_data?.category_list?.find(
    item => item.category_code === category_code
  );

  // 合并站点的其它信息到类目中
  category_data.website_code = site_data.website_code;
  category_data.website_name = site_data.website_name;
  category_data.site_logo_url = site_data.website_img_url;

  console.debug('category_data', category_data);

  return category_data;
}

// 获取所有全局配置脚本数据
export async function fetch_all_global_config() {
  try {
    let res = await get_global_config();
    if (res.code === 'ok') {
      localStorage.setItem('global_configs', JSON.stringify(res.data));
      return res.data;
    } else {
      message.error(`获取全局配置脚本数据失败: ${res.message}`);
    }
  } catch (err) {
    message.error(`拉取最新全局配置脚本数据失败: ${err}`);
  }
}

// 根据脚本 Key 获取全局配置脚本数据
export async function get_global_config_by_key(key) {
  try {
    if (!localStorage.getItem('global_configs')) {
      await fetch_all_global_config();
    }
    return JSON.parse(localStorage.getItem('global_configs')).find(
      item => item.configKey === key
    );
  } catch (err) {
    console.error('get_global_config_by_key error', err);
    return null;
  }
}

// 根据脚本 Key 更新全局配置脚本数据
export async function update_global_config_by_key(
  key,
  value,
  extra_info,
  params_json
) {
  try {
    await update_global_config([
      {
        configKey: key,
        configValue: value,
        extraInfo: extra_info,
        paramsJson: params_json,
      },
    ]);
    await fetch_all_global_config();
    message.success(`更新全局配置脚本数据成功`);
  } catch (err) {
    message.error(`更新全局配置脚本数据失败: ${err}`);
  }
}

// 拉取所有站点脚本信息
export async function fetch_all_site_scripts() {
  let res = await website_list();
  if (res.code === 'ok') {
    localStorage.setItem('website_scripts', JSON.stringify(res.data));
    return res.data;
  } else {
    message.error(`获取站点脚本信息失败: ${res.message}`);
  }
}

// 获取站点脚本信息
export async function get_site_script_data(site_code) {
  try {
    if (!localStorage.getItem('website_scripts')) {
      await fetch_all_site_scripts();
    }
    return JSON.parse(localStorage.getItem('website_scripts')).find(
      item => item.websiteCode === site_code
    );
  } catch (err) {
    message.error(`获取站点脚本信息失败: ${err}`);
    console.error('get_site_script_data error', err);
  }
}

// 更新站点脚本信息
export async function update_site_script_data(site_code, script) {
  try {
    let script_key = script.description;
    let res = await script_update({
      id: script.id,
      script: script,
      websiteCode: site_code,
    });
    // 更新缓存的脚本
    let cache_site_scripts = JSON.parse(
      localStorage.getItem('website_scripts')
    );
    cache_site_scripts
      .find(site => site.websiteCode === site_code)
      .scripts.find(item => item.description === script_key).content =
      script.content;
    localStorage.setItem('website_scripts', JSON.stringify(cache_site_scripts));
  } catch (err) {
    message.error(`更新站点脚本信息失败: ${err}`);
  }
}

// 清除除了用户 token 以外的所有本地存储数据
export function clear_local_storage() {
  let user_token = localStorage.getItem('user_token');
  localStorage.clear();
  localStorage.setItem('user_token', user_token);
}

// debug 用显示对象信息
function debug_show(item) {
  console.debug('debug ->', item);
  return item;
}
